package com.central.scheduler.api.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.central.common.model.PageResult;
import com.central.common.model.Result;
import com.central.common.model.SysUser;
import com.central.common.service.impl.SuperServiceImpl;
import com.central.common.utils.UserRoleUtil;
import com.central.scheduler.api.service.IProcessInstanceService;
import com.central.scheduler.api.service.ITaskInstanceService;
import com.central.scheduler.common.enums.ExecutionStatus;
import com.central.scheduler.dao.mapper.ProcessInstanceMapper;
import com.central.scheduler.dao.mapper.TaskInstanceMapper;
import com.central.scheduler.dao.model.ProcessInstance;
import com.central.scheduler.dao.model.TaskInstance;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


/**
 * @author Tindy
 * @date 2021/6/24
 * @describe
 */
@Slf4j
@Service
public class TaskInstanceServiceImpl extends SuperServiceImpl<TaskInstanceMapper, TaskInstance> implements ITaskInstanceService {

    @Override
    public PageResult<TaskInstance> queryTaskInstances(Map<String, Object> params) {
        Page<TaskInstance> page = new Page<>(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"));
        List<TaskInstance> list = baseMapper.queryTaskInstances(page, params);
        long total = page.getTotal();
        return PageResult.<TaskInstance>builder().data(list).code(0).count(total).build();
    }

    @Override
    public List<TaskInstance> findTaskInstances(Long proId, Long processInstanceId) {
        return baseMapper.findTaskInstances(proId, processInstanceId);
    }

    /**
     * change one task instance's state from failure to forced success
     *
     * @param user           login user
     * @param taskInstanceId task instance id
     * @return the result code and msg
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result forceTaskSuccess(SysUser user, Long taskInstanceId) {

        // check whether the task instance can be found
        TaskInstance task = baseMapper.selectById(taskInstanceId);
        if (task == null) return Result.failed("操作失败，作业实例未存在");
        //检查用户是否有权限
        if (!checkOperationPermission(user, task)) return Result.failed("操作失败，用户权限不足");

        // check whether the task instance state type is failure or cancel
        if (!task.getState().typeIsFailure() && !task.getState().typeIsCancel())
            return Result.failed("操作失败，当前实例状态不可强制成功");

        // change the state of the task instance
        task.setState(ExecutionStatus.FORCED_SUCCESS);
        baseMapper.updateById(task);
        return Result.succeed("操作成功");
    }

    /**
     * 只有项目管理员和作业流执行人拥有修改权限
     *
     * @param user
     * @param taskInstance
     * @return
     */
    private boolean checkOperationPermission(SysUser user, TaskInstance taskInstance) {
        if (user.getCurrentProjectId().equals(taskInstance.getProId()) && UserRoleUtil.checkProAdmin(user.getProRoles()))
            return true;
        if (taskInstance.getUsername().equals(user.getUsername())) return true;
        return false;
    }

}
